package weixin;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Yangu
 * @Created time: 2021/2/28 4:33
 * @Description :
 */
public class AccessTokenTest {

    private String appId = "wxae85d80a4ab89aa8";

    private String appSecret = "5091f95c21169a847be32ef530af469e";

    private String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";

    @Test
    public void test() {
        Map<String, Object> params = convertGetBaseAccessToken();
        String url = getAccessTokenUrl + "?appid={appid}&secret={secret}&grant_type={grant_type}";
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class, params);
        if(responseEntity == null) {
            log.error("call weixin getBaseAccessToken responseEntity is null");
            throw new PldDataIntelligentException(ResultCode.WEI_XIN_INTERFACE_EXCEPTION);
        }
        WeixinAccessTokenResponse weixinAccessTokenResponse = JSON.parseObject(responseEntity.getBody(), WeixinAccessTokenResponse.class);
        if(HttpStatus.OK.equals(responseEntity.getStatusCode()) && !StringUtils.isEmpty(weixinAccessTokenResponse.getAccess_token())) {
            log.info("getBaseAccessToken is ok. weixinAccessTokenResponse:{}", weixinAccessTokenResponse);
            //往后推200s,比微信的有效期推后一些
            redisTemplate.opsForValue().set("access_token", weixinAccessTokenResponse.getAccess_token(), weixinAccessTokenResponse.getExpires_in() - 200, TimeUnit.SECONDS);
            return weixinAccessTokenResponse.getAccess_token();
        } else {
            log.error("call weixin getBaseAccessToken responseEntity not success responseEntity:{}", responseEntity);
            throw new PldDataIntelligentException(ResultCode.WEI_XIN_INTERFACE_EXCEPTION);
        }
    }


    private Map<String, Object> convertGetBaseAccessToken() {
        Map<String, Object> map = new HashMap<>();
        map.put(WeixinConstant.WEIXIN_APP_ID, appId);
        map.put(WeixinConstant.WEIXIN_APP_SECRET, appSecret);
        map.put(WeixinConstant.WEIXIN_GRANT_TYPE, WeixinConstant.WEIXIN_GRANT_TYPE_CLIENT_CREDENTIAL);
        return map;
    }
}
